﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using System.ServiceProcess;
using NetFwTypeLib;
using System.Net.Configuration;

namespace RDP2
{
    public partial class Form1 : Form
    {
        private static readonly string hklmkey = @"SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp";
        public Form1()
        {
            InitializeComponent();
            GetPort();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int portnumber = 0;
            if (int.TryParse(textBox1.Text, out portnumber) && portnumber > 1024 && portnumber < 65535)
            {
                SetPort(portnumber);
                string name= "RDP"+portnumber.ToString();
                NetFwAddPorts(name, portnumber, "TCP");
                RestartRDP();
            }
            else {
                MessageBox.Show("输入的端口号不规范，\r\n端口号必须为大于1024且小于65535的整数");
            }


        }

      

        // 读注册表
        private  void GetPort()
        {
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(hklmkey, true))
            {

                
                    try
                    {
                    textBox1.Text= key.GetValue("PortNumber").ToString();
                     
                    }
                    catch (Exception ee)
                    {
                        MessageBox.Show(ee.Message);
                    }
                    finally
                    {
                        key.Close();
                    }


            }
        }
        // 写注册表
        private static void SetPort(int portnumber)
        {
            NTAccount name = new NTAccount(Environment.UserDomainName, Environment.UserName);
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(hklmkey, true))
            {
                if (key != null) {
                    try
                    {
                        RegistrySecurity rs = key.GetAccessControl();
                        RegistryAccessRule denyRule = rs
                            .GetAccessRules(true, false, typeof(NTAccount))
                        .OfType<RegistryAccessRule>()
                            .FirstOrDefault(r => r.AccessControlType == AccessControlType.Deny && (r.IdentityReference as NTAccount) == name);

                        if (denyRule != null && rs.RemoveAccessRule(denyRule))
                        {
                            key.SetAccessControl(rs);
                        }
                        key.SetValue("PortNumber", portnumber, RegistryValueKind.DWord);
                        MessageBox.Show("远程桌面端口号已更新");
                    }
                    catch (Exception ee)
                    {
                        string msg = String.Format("{0}:{1}", ee.GetType(), ee.Message);
                        MessageBox.Show(msg);
                    }
                    finally
                    {
                        key.Close();
                    }
                }

          
            }
        }
        /// <summary>
        /// 添加防火墙例外端口
        /// </summary>
        /// <param name="name">名称</param>
        /// <param name="port">端口</param>
        /// <param name="protocol">协议(TCP、UDP)</param>
        public static void NetFwAddPorts(string name, int port, string protocol)
        {
            //创建firewall管理类的实例
            INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));

            INetFwOpenPort objPort = (INetFwOpenPort)Activator.CreateInstance(
                Type.GetTypeFromProgID("HNetCfg.FwOpenPort"));

            objPort.Name = name;
            objPort.Port = port;
            if (protocol.ToUpper() == "TCP")
            {
                objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            }
            else
            {
                objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
            }
            objPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
            objPort.Enabled = true;

            bool exist = false;
            //加入到防火墙的管理策略
            foreach (INetFwOpenPort mPort in netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts)
            {

                if (objPort == mPort)
                {
                    exist = true;
                    break;
                }
            }
            if (exist)
            {
                System.Windows.Forms.MessageBox.Show("exist");
            }
            if (!exist) netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(objPort);
        }
        // 重启远程桌面服务
        private static void RestartRDP()
        { 
            ServiceController sc = new ServiceController("TermService");
            try
            {
                // 尝试停止服务
                
                sc.Stop();
                sc.WaitForStatus(ServiceControllerStatus.Stopped);

               

                // 重新启动服务
              
                sc.Start();
                sc.WaitForStatus(ServiceControllerStatus.Running);

                
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine("Service could not be found on this machine.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("远程桌面服务重启失败: " + ex.Message);
            }
        }
    }
}
